#region File Description
//-----------------------------------------------------------------------------
// MenuScreen.cs
//
// XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
#endregion

namespace PokeTD
{
    /// <summary>
    /// Base class for screens that contain a menu of options. The user can
    /// move up and down to select an entry, or cancel to back out of the screen.
    /// </summary>
    abstract class MenuScreen : GameScreen
    {
        ContentManager content;
        Texture2D logo;
        Texture2D menulayer;

        List<MenuEntry> menuEntries = new List<MenuEntry>();
        int lastactive = 0;
        int selectedEntry = 0;
        string menuTitle;
        SoundEffect MenuHover;
        SoundEffect MenuClick;

        InputAction menuUp;
        InputAction menuDown;
        InputAction menuSelect;
        InputAction menuCancel;
        MouseState prevstate = Mouse.GetState();
        Song rising;

        /// <summary>
        /// Gets the list of menu entries, so derived classes can add
        /// or change the menu contents.
        /// </summary>
        protected IList<MenuEntry> MenuEntries
        {
            get { return menuEntries; }
        }
        protected int SelectedEntry {
            get { return selectedEntry; }
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        public MenuScreen(string menuTitle)
        {
            this.menuTitle = menuTitle;

            

            TransitionOnTime = TimeSpan.FromSeconds(0.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);

            menuUp = new InputAction(
                new Buttons[] { Buttons.DPadUp, Buttons.LeftThumbstickUp }, 
                new Keys[] { Keys.Up },
                true);
            menuDown = new InputAction(
                new Buttons[] { Buttons.DPadDown, Buttons.LeftThumbstickDown },
                new Keys[] { Keys.Down },
                true);
            menuSelect = new InputAction(
                new Buttons[] { Buttons.A, Buttons.Start },
                new Keys[] { Keys.Enter, Keys.Space },
                true);
            menuCancel = new InputAction(
                new Buttons[] { Buttons.B, Buttons.Back },
                new Keys[] { Keys.Escape },
                true);
        }

        public override void Activate(bool instancePreserved) {
            if (!instancePreserved) {
                if (content == null)
                    content = new ContentManager(ScreenManager.Game.Services, "Content");

                logo = content.Load<Texture2D>("Menu\\logo");
                menulayer = CreateRectangle(700,700, ScreenManager.Game.GraphicsDevice, new Color(0,0,20, 200));
                MenuHover = content.Load<SoundEffect>("Sfx/pop1");
                MenuClick = content.Load<SoundEffect>("Sfx/pop2");
                rising = content.Load<Song>("Music/Rising");
            }
        }

        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public override void HandleInput(GameTime gameTime, InputState input)
        {
            // For input tests we pass in our ControllingPlayer, which may
            // either be null (to accept input from any player) or a specific index.
            // If we pass a null controlling player, the InputState helper returns to
            // us which player actually provided the input. We pass that through to
            // OnSelectEntry and OnCancel, so they can tell which player triggered them.
            MouseState state = Mouse.GetState();
            Vector2 hoverbounds = ScreenManager.Font.MeasureString(menuEntries[0].Text);
            int startx = (int)menuEntries[0].Position.X;
            for (int i = 1; i < menuEntries.Count; i++) {
                int temp = (int)ScreenManager.Font.MeasureString(menuEntries[i].Text).X;
                if (temp > hoverbounds.X) hoverbounds.X = temp;
                if (menuEntries[i].Position.X < startx) startx = (int)menuEntries[i].Position.X;
            }
            for (int i = 0; i < menuEntries.Count; i++) {
                if (new Rectangle(startx, (int)menuEntries[i].Position.Y, (int)hoverbounds.X, (int)hoverbounds.Y).Contains(new Point(state.X, state.Y))) {
                    selectedEntry = i;
                    if (lastactive != i)
                    {
                        MenuHover.Play();
                    }
                    lastactive = i;
                    if (prevstate.LeftButton == ButtonState.Released && state.LeftButton == ButtonState.Pressed) {
                        OnSelectEntry(selectedEntry);
                        MenuClick.Play();
                    }
                    break;
                }
            }
            prevstate = Mouse.GetState();

            // Move to the previous menu entry?
            if (menuUp.Evaluate(input))
            {
                selectedEntry--;

                if (selectedEntry < 0)
                    selectedEntry = menuEntries.Count - 1;

                MenuHover.Play();
            }

            // Move to the next menu entry?
            if (menuDown.Evaluate(input))
            {
                selectedEntry++;

                if (selectedEntry >= menuEntries.Count)
                    selectedEntry = 0;

                MenuHover.Play();
            }

            if (menuSelect.Evaluate(input))
            {
                OnSelectEntry(selectedEntry);
                MenuClick.Play();
            }
            else if (menuCancel.Evaluate(input))
            {
                OnCancel();
            }
        }


        /// <summary>
        /// Handler for when the user has chosen a menu entry.
        /// </summary>
        protected virtual void OnSelectEntry(int entryIndex)
        {
            menuEntries[entryIndex].OnSelectEntry();
        }


        /// <summary>
        /// Handler for when the user has cancelled the menu.
        /// </summary>
        protected virtual void OnCancel()
        {
            ExitScreen();
        }


        /// <summary>
        /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
        /// </summary>
        protected void OnCancel(object sender, EventArgs e)
        {
            OnCancel();
        }


        #region Update and Draw


        /// <summary>
        /// Allows the screen the chance to position the menu entries. By default
        /// all menu entries are lined up in a vertical list, centered on the screen.
        /// </summary>
        protected virtual void UpdateMenuEntryLocations()
        {
            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            // start at Y = 350; each X value is generated per entry
            Vector2 position = new Vector2(0f, 300f);

            // update each menu entry's location in turn
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];
                
                // each entry is to be centered horizontally
                position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2;

                if (ScreenState == ScreenState.TransitionOn)
                    position.X -= transitionOffset * 256;
                else
                    position.X += transitionOffset * 512;

                // set the entry's position
                menuEntry.Position = position;

                // move down for the next entry the size of this entry
                position.Y += menuEntry.GetHeight(this);
            }
        }


        /// <summary>
        /// Updates the menu.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            if (!Globals.mediaPlaying)
            {
                MediaPlayer.Play(rising);
                Globals.mediaPlaying = true;
            }
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            // Update each nested MenuEntry object.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);

                menuEntries[i].Update(this, isSelected, gameTime);
            }
        }


        /// <summary>
        /// Draws the menu.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            // make sure our entries are in the right place before we draw them
            UpdateMenuEntryLocations();

            GraphicsDevice graphics = ScreenManager.GraphicsDevice;
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            SpriteFont font = ScreenManager.Font;

            spriteBatch.Begin();

            // Draw Menu Entry Background

            int w = (from entry in menuEntries
                     orderby entry.GetWidth(this) descending
                     select (int)entry.Position.X).ElementAt(0);


            Vector2 Startpos = new Vector2(w - 10, menuEntries[0].Position.Y - 10);

            //loop through entries, find the biggest.
            int bx = 0;
            foreach (MenuEntry m in menuEntries)
            {
                if (m.GetWidth(this) > bx)
                    bx = m.GetWidth(this);
            }

            //Vector2 Endpos = menuEntries[menuEntries.Count - 1].Position + new Vector2(bx + 10, menuEntries[menuEntries.Count - 1].GetHeight(this) + 10);
            Vector2 Endpos = new Vector2(Startpos.X + bx + 20, menuEntries[menuEntries.Count - 1].Position.Y + menuEntries[menuEntries.Count - 1].GetHeight(this) + 10);

            spriteBatch.Draw(menulayer, new Rectangle((int)Startpos.X, (int)Startpos.Y, (int)Endpos.X - (int)Startpos.X, (int)Endpos.Y - (int)Startpos.Y), Color.White);
            

            // Draw each menu entry in turn.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];

                bool isSelected = IsActive && (i == selectedEntry);

                menuEntry.Draw(this, isSelected, gameTime);
            }

            // Make the menu slide into place during transitions, using a
            // power curve to make things look more interesting (this makes
            // the movement slow down as it nears the end).
            float transitionOffset = (float)Math.Pow(TransitionPosition, 2);

            // Draw the menu title centered on the screen
            if (menuTitle != "") {
                Vector2 titlePosition = new Vector2(graphics.Viewport.Width / 2, 80);
                Vector2 titleOrigin = font.MeasureString(menuTitle) / 2;
                Color titleColor = new Color(192, 192, 192) * TransitionAlpha;
                float titleScale = 1.25f;
                titlePosition.Y -= transitionOffset * 100;
                
                spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0,
                                       titleOrigin, titleScale, SpriteEffects.None, 0);
            } else {
                Vector2 logoPosition = new Vector2(graphics.Viewport.Width / 2 - logo.Width / 2, 20);
                spriteBatch.Draw(logo, logoPosition, Color.White);
            }
            spriteBatch.End();
        }

        public Texture2D CreateRectangle(int width, int height, GraphicsDevice gd, Color c)
        {
            //Texture2D rectangleTexture = new Texture2D(this, width, height, 1, TextureUsage.None, SurfaceFormat.Color);// create the rectangle texture, ,but it will have no color! lets fix that
            Texture2D rectangleTexture = new Texture2D(gd, width, height);
            Color[] color = new Color[width * height];//set the color to the amount of pixels

            for (int i = 0; i < color.Length; i++)//loop through all the colors setting them to whatever values we want
            {
                color[i] = c;
            }
            rectangleTexture.SetData(color);//set the color data on the texture
            return rectangleTexture;
        }

        #endregion
    }
}
